package com.xunshangwang.pinhaohuo.ui.activities;

import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.xunshangwang.pinhaohuo.R;
import com.xunshangwang.pinhaohuo.adapters.GoodsAdapter;
import com.xunshangwang.pinhaohuo.decorations.GoodsItemDecoration;
import com.xunshangwang.pinhaohuo.entity.Goods;
import com.xunshangwang.pinhaohuo.http.HttpTool;
import com.xunshangwang.pinhaohuo.http.JsonHttpHandler;
import com.xunshangwang.pinhaohuo.widgets.LMPageRecyclerView;
import com.xunshangwang.pinhaohuo.widgets.RefreshLayout;

import org.json.JSONObject;

import java.util.List;

import cz.msebera.android.httpclient.Header;
import tool.library.adapter.BaseRecyclerAdapter;
import tool.library.widget.LoadRecyclerView;

/**
 * Created by xzp on 16/3/1.
 */
public class GoodsListActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener,
        BaseRecyclerAdapter.OnItemClickListener,LoadRecyclerView.OnLoadListener{
    private String mAttrId;
    private String mAttrName;
    private LMPageRecyclerView mRecycler;
    private RefreshLayout mRefresh;
    private GoodsAdapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_list);
        mAttrId=getIntent().getStringExtra("attrId");
        mAttrName=getIntent().getStringExtra("attrName");
        getTitleText().setText(mAttrName);
        mRecycler= (LMPageRecyclerView) this.findViewById(R.id.goods_list);
        mRefresh= (RefreshLayout) this.findViewById(R.id.refresh_layout);
        mAdapter=new GoodsAdapter(this);
        mRecycler.setLayoutManager(new LinearLayoutManager(this));
        mRecycler.addItemDecoration(new GoodsItemDecoration(this) {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                if (parent.getChildAdapterPosition(view) < parent.getAdapter().getItemCount() - 1)
                    super.getItemOffsets(outRect, view, parent, state);
            }
        });
        mRecycler.setAdapter(mAdapter);
        mRefresh.setOnRefreshListener(this);
        mRecycler.setOnLoadListener(this);
        mAdapter.setOnItemClickListener(this);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefresh.setRefreshing(true);
                onRefresh();
            }
        },150);
    }

    @Override
    public void onItemClick(BaseRecyclerAdapter adapter, View item, int position) {
        Intent intent=new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("pin://www.xunshangwang.com/goods/detail?id="+mAdapter.getList().get(position).getGoods_id()));
        startActivity(intent);
    }

    @Override
    public void onLoad(LoadRecyclerView recyclerView) {
        loadGoodsList();
    }

    @Override
    public void onRefresh() {
        refreshGoodsList();
    }
    public void refreshGoodsList(){
        StringBuilder builder=new StringBuilder("?g=Api&m=Extends&a=havasAttrGoodsList");
        builder.append("&attr_id="+mAttrId);
        builder.append("&p=1");
        HttpTool.get(this, builder.toString(), new JsonHttpHandler<List<Goods>>() {
            @Override
            public List<Goods> parseData(JSONObject object) throws Throwable {
                mRecycler.setCount(object.has("count")?object.getInt("count"):0);
                return JSON.parseArray(object.getString("goods"), Goods.class);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mRefresh.setRefreshing(false);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, List<Goods> response) {
                mAdapter.setList(response);
                mRecycler.resetPage();
            }
        });
    }
    public void loadGoodsList(){
        StringBuilder builder=new StringBuilder("?g=Api&m=Extends&a=havasAttrGoodsList");
        builder.append("&attr_id="+mAttrId);
        builder.append("&p="+(mRecycler.getPage()+1));
        HttpTool.get(this, builder.toString(), new JsonHttpHandler<List<Goods>>() {
            @Override
            public List<Goods> parseData(JSONObject object) throws Throwable {
                mRecycler.setCount(object.has("count")?object.getInt("count"):0);
                return JSON.parseArray(object.getString("goods"),Goods.class);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, List<Goods> errorResponse) {
                super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
                mRecycler.loadFinish(false);
            }
            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, List<Goods> response) {
                mAdapter.addAll(response);
                mRecycler.loadFinish(true);
            }
        });
    }
}
